<?php

namespace App\Admin\Forms;

use App\Models\Season;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Http\JsonResponse;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Exception;
use Illuminate\Support\Facades\DB;

class ReplicateSeasonForm extends Form implements LazyRenderable
{
    use LazyWidget;

    public function handle(array $input): JsonResponse
    {
        try {
            DB::transaction(function () use ($input) {
                $model = Season::find($this->payload['season_id']);

                $new = $model->replicate();

                $new->title = $input['title'];
                $new->save();

                foreach ($model->gifts as $gift) {
                    $gift = $gift->toArray();
                    unset($gift['id']);
                    $new->gifts()->create($gift);
                }

                foreach ($model->designs as $design) {
                    $design = $design->toArray();
                    unset($design['id']);
                    $new->designs()->create($design);
                }
            });

            return $this->response()->success('赛季复制完成')->refresh();
        } catch (Exception) {
            return $this->response()->error('赛季复制出错了')->refresh();
        }
    }

    public function form(): void
    {
        $this->text('title', '新赛季标题')
            ->required();
    }
}
